﻿using e_commerce.BLL.Services;
using e_commerce.BLL.Data;
using e_commerce.BLL.Services.Client;
using e_commerce.Foreground.Models;
using e_commerce.Models;
using PagedList;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Net.Mail;
using e_commerce.BLL.Models;

namespace e_commerce.Foreground.Controllers
{
    public class PageController : Controller
    {
        private GoodsManager _gManager;
        private OrderService _oService;
        private DeliveryManager _dManager;
        public PageController()
        {
            _gManager = new GoodsManager();
            _dManager = new DeliveryManager();
            _oService = new OrderService();
        }
        // GET: Page
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Home()
        {
            var mobilePhone = _gManager.GetGoodsByCount(10, (int)GoodsCategory.MobilePhone);
            var otherParts = _gManager.GetGoodsByCount(10, (int)GoodsCategory.OtherParts);
            List<Goods> list = new List<Goods>();
            list.AddRange(SwitchGoodsInfoToGoods(mobilePhone).ToList());
            list.First().IsFirst = true;
            list.AddRange(SwitchGoodsInfoToGoods(otherParts).ToList());
            list.Skip(mobilePhone.Count()).First().IsFirst = true;
            return View(list);
        }

        private IEnumerable<Goods> SwitchGoodsInfoToGoods(IEnumerable<GoodsInfo> goods)
        {
            return goods.Select(m => new Goods()
            {
                GoodsId = m.GoodsId,
                GoodsName = m.GoodsName,
                Price = m.Price,
                Details = m.Details,
                Deal = m.Deal,
                Images = m.Image.First().ImageSrc,
                Category = m.Category,
            });
        }
        
        public ActionResult Detail(int goodsId)
        {
            var goods = _gManager.GetGoodsById(goodsId);
            List<string> imagesUrl = new List<string>();
            foreach(var image in goods.Image)
            {
                imagesUrl.Add(image.ImageSrc);
            }
            GoodsDetail goodsModel = new GoodsDetail()
            {
                GoodsID = goods.GoodsId,
                GoodsName = goods.GoodsName,
                Price = goods.Price,
                Detail = goods.Details,
                Images = imagesUrl,
            };
            return View(goodsModel);
        }

        public ActionResult Introduce()
        {
            return View();
        }
        
        public ActionResult Order(int goodsId, int count)
        {
            var client = Session["Client"] as ClientModel;
            if(client == null)
            {
                var url = "/Page/Detail?goodsId=" + goodsId;
                return RedirectToAction("Login", "Account",new { callback =url});
            }
            var goods = _gManager.GetGoodsById(goodsId);
            Models.Order model = new Models.Order()
            {
                ClientId = client.ClientId,
                GoodsId = goodsId,
                GoodsName = goods.GoodsName,
                Price = goods.Price,
                Count = count,
                Icon = goods.Image.First().ImageSrc
            };
            return View(model);
        }

        [HandleError(ExceptionType = typeof(Exception))]
        public ActionResult List(int category = 0,int page = 1)
        {
            int pageSize = 24;
            List<Goods> list = _gManager.GetGoodsByCategory(category)
                .Select(g=> new Goods()
                {
                    GoodsId = g.GoodsId,
                    GoodsName = g.GoodsName,
                    Price = g.Price,
                    Deal = g.Deal,
                    Details = g.Details,
                    Images = g.Image.First().ImageSrc,
                }).ToList();
            return View(list.ToPagedList(page,pageSize));
        }

        [HttpPost]
        [HandleError(ExceptionType = typeof(Exception))]
        public JsonResult PayOrder(Models.Order model)
        {
            JsonResult res = new JsonResult();
            var success = "";
            var error = "";
            var orderId = "";
            try
            {
                var client = Session["Client"] as ClientModel;
                var goods = _gManager.GetGoodsById(model.GoodsId);
                var deliver = _dManager.GetDeliveryById(model.DeliverId);
                BLL.Data.Order order = new BLL.Data.Order()
                {
                    ClientId = client.ClientId,
                    GoodsId = model.GoodsId,
                    GoodsName = goods.GoodsName,
                    Price = goods.Price,
                    Count = model.Count,
                    DeliveryAddress = deliver.DetailedAddress,
                    Consignee = deliver.Consignee,
                    PhoneNumber = deliver.PhoneNumber,
                    ClientRemark = model.ClientMark,
                };
                orderId =  _oService.CreateOrder(order);
                success = "订单创建成功";
            }catch(Exception ex)
            {
                error = ex.Message;
            }
            res.Data = new { success,orderId, error };
            return res;
        }

        [HandleError(ExceptionType =typeof(Exception))]
        public ActionResult PayOrder(string orderId)
        {
            return View();
        }

        [HttpPost]
        public JsonResult OrderPayment(string orderId,string password)
        {
            JsonResult res = new JsonResult();
            var success = "";
            var error = "";
            try
            {
                var client = Session["Client"] as ClientModel;
                _oService.Payment(orderId, client.ClientId,password);
                success = "支付成功";
            }catch(Exception ex)
            {
                error = ex.Message;
            }

            res.Data = new { success, error };
            return res;
        }

        [HandleError(ExceptionType = typeof(Exception))]
        public ActionResult DeliverComponent()
        {
            var client = Session["Client"] as e_commerce.Models.ClientModel;
            List<Models.DeliveryInfo> list = _dManager.GetDeliveryByClientId(client.ClientId)
                .Select(d => new Models.DeliveryInfo()
                {
                    Id = d.Id,
                    Name = d.Consignee,
                    Address = d.DetailedAddress,
                    PhoneNumber = d.PhoneNumber,
                    IsDefault = d.IsDefault,
                }).ToList();
            return PartialView(list);
        }
    }
}